package de.herzog.bbp.model.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import de.herzog.bbp.model.Klasse;

public class KlasseDAO extends AbstractDAO {

	public static List<Klasse> loadAll() {
		@SuppressWarnings("unchecked")
		List<Klasse> list = getSession().createCriteria(Klasse.class).list();
		return list;
	}

	public static Klasse loadById(Integer id) {
		return (Klasse) getSession().load(Klasse.class, id);
	}

	public static List<Klasse> loadByName(String name) {
		Criteria criteria = getSession().createCriteria(Klasse.class);
		criteria.add(Restrictions.eq("name", name));
		@SuppressWarnings("unchecked")
		List<Klasse> list = criteria.list();
		return list;
	}

	public static Klasse getByName(String name) {
		List<Klasse> list = loadByName(name);
		if (list.size() > 1)
			throw new IllegalStateException("Duplicate Klasse with name " + name);
		if (list.size() == 1) {
			return list.get(0);
		} else {
			Klasse klasse = new Klasse(name, name, 2);
			persist(klasse);
			return klasse;
		}
	}
}
